/*
 * name:表单提交 SubmitForm
 * description:提交前获取各校验器disabled属性
 * author:yanmu.wj@taobao.com
 * date:2011-11-24
 */
KISSY.add('SubmitForm',function(S,Tip){
    var SubmitForm = function(cfg){
        this.form = cfg.form && S.one(cfg.form);
        this.tip = cfg.tip && S.one(cfg.tip) ? Tip(cfg.tip) : null;

        //trigger主要用于触发form的submit时间，对于必须校验后才能提交form，不使用submit button，禁用JS后form将不能提交
        this.trigger = cfg.trigger && S.one(cfg.trigger) ? Tip(cfg.trigger) : null;

        //针对CheckTypeSelect校验器组合会实时变化，传入方法获取当前checkers
        this.checkers = S.isArray(cfg.checkers) || S.isFunction(cfg.checkers) ? cfg.checkers : [];

        this.toid = 0;

        this.disabledMsg = S.isString(cfg.disabledMsg) ? cfg.disabledMsg : '信息输入有误，请重新输入！';
        this.checkerDisabledMsg = '';
        this.disabled = false;
    };
    var _SubmitForm = function(cfg){
        return new SubmitForm(cfg);
    };
    S.augment(SubmitForm,{
        init:function(){
            if(!this.form || !this.tip) return;

            var self = this;

            if(this.trigger){
                this.trigger.on('click',function(){
                    self.form.fire('submit');
                })
            }

            this.form.on('submit',function(){
                self.check();
                if(self.disabled){
                    self.tip.error(self.checkerDisabledMsg || this.disabledMsg);
                    self.hideTip();
                    return false;
                }
                return true;
            });

            return this;
        },
        check:function(){
            //每次校验前重置disabled属性
            this.disabled = false;

            //如果有提供获取checkers的方法，则调用getCheckersFn
            var checkers = S.isFunction(this.checkers) ? this.checkers() : this.checkers;

            if(!checkers.length) return;
                        
            for(var i=0,l=checkers.length;i<l;i++){
                if(checkers[i].disabled){
                    this.disabled = true;
                    if(checkers[i].disabledMsg) this.checkerDisabledMsg = checkers[i].disabledMsg;
                    break;
                }
            }
        },
        hideTip:function(){
            var self = this;

            this.toid && window.clearTimeout(this.toid);
            this.toid = window.setTimeout(function(){
                self.tip.hide();
            },2000);
        }
    });

    return _SubmitForm;
},{
    requires:['Message']
});
